<?php
/**
 * User: 昊天||597767865@qq.com
 * Date: 2019/8/30
 * Time: 15:49
 */
namespace backend\controllers;
use backend\models\Category;
use yii\web\Controller;
use Yii;
class CategoryController extends BaseController
{
    public function actionIndex()
    {
        $search = Yii::$app->request->get('search');
        $query =  Category::find();
        if($search['name']){
            $query = $query->andWhere(['like','name',$search['name']]);
        }
        $grade = $query->orderBy('level asc')->asArray()->all();
        $grade = Category::isChildren($grade);
        $prefix = '&nbsp;&nbsp;&nbsp;&nbsp;';
        return $this->render('index',compact('grade','prefix','search'));
    }

    public function actionCreate()
    {
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $grade = new Category();
            $res = $grade->create($post);
            if ($res['status'] != 200) {
                return $this->json(100, $res['msg']);
            }
            return $this->json(200, $res['msg']);
        }
        $fid = (int)Yii::$app->request->get('fid');
        $grade = Category::find()->orderBy('level asc')->asArray()->all();
        $gradeTree = Category::categoryTree($grade);
        return $this->render('create',compact('gradeTree','fid'));
    }

    public function actionEdit()
    {
        $id = (int)Yii::$app->request->post('id');
        $name = Yii::$app->request->post('name');
        $model = Category::findOne($id);
        $model->name = $name;
        if($model->save()){
            return $this->json(200, '修改成功');
        }else{
            $error = array_values($model->getFirstErrors())[0];
            return $this->json(100, $error);
        }
    }

    /**
     * 删除
     * @return string
     */
    public function actionDel()
    {
        $id = (int)Yii::$app->request->get('id');
        $model = Category::findOne(['fid'=>$id]);
        if ($model) {
            return $this->json(100, '含有子菜单，禁止删除');
        }
        $res = Category::deleteAll(['id'=>$id]);
        if (!$res) {
            return $this->json(100, '删除失败');
        }
        return $this->json(200, '删除成功');
    }

    /**
     * 批量删除
     * @return string
     */
    public function actionBatchDel()
    {
        $idArr = Yii::$app->request->get('idArr');
        foreach ($idArr as $id) {
            $model = Category::findOne(['fid' => $id]);
            if ($model) {
                return $this->json(100, '含有子菜单，禁止删除');
            }
        }
        $res = Category::deleteAll(['in', 'id', $idArr]);
        if (!$res) {
            return $this->json(100, '批量删除失败');
        }
        return $this->json(200, '批量删除成功');
    }
}
